package org.goldfish.distributed_framework.server;

import org.goldfish.distributed_framework.api.Service;
import org.goldfish.distributed_framework.client.RpcRequest;
import org.goldfish.distributed_framework.client.RpcResponse;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

public class ServiceProvider {
    // 当前只维护一个服务实例
    private static Service serviceInstance;

    /**
     * 注册一个服务实现。
     */
    public static void register(Service service) {
        serviceInstance = service;
    }

    /**
     * 调用已注册的服务
     */
    public static RpcResponse invoke(RpcRequest request) {
        if (serviceInstance != null) {
            return serviceInstance.handleRequest(request);
        }
        return RpcResponse.failure("Service not found");
    }

    private static final Map<String, Service> services = new ConcurrentHashMap<>();

    // 注册服务
    public static void register(String serviceName, Service service) {
        serviceInstance=service;
        services.put(serviceName, service);
        System.out.println("服务注册成功: " + serviceName);
    }

    // 获取服务
    public static Service getService(String serviceName) {
        return services.get(serviceName);
    }

    // 判断服务是否已注册
    public static boolean isServiceRegistered(String serviceName) {
        return services.containsKey(serviceName);
    }
}

